import {defineStore} from 'pinia'
import { fetchUserAddresses, createAddress, updateAddress, deleteAddress } from '@/api/mockData'

export const useAddressStore = defineStore('address', {
    state: () => ({
        addresses: [],
        isLoading: false,
        error: null
    }),
    actions: {
        async fetchAddresses() {
            try {
                this.isLoading = true
                this.error = null

                // 1. 首先尝试从API获取
                try {
                    const response = await fetchUserAddresses() // 修改此处
                    this.addresses = response
                    this.saveToLocalStorage()
                    return
                } catch (apiError) {
                    console.warn('API请求失败，尝试使用本地缓存:', apiError)
                }

                // 2. API失败时使用本地缓存
                const localAddresses = localStorage.getItem('user_addresses')
                if (localAddresses) {
                    this.addresses = JSON.parse(localAddresses)
                    return
                }

                // 3. 都没有数据时使用默认空数组
                this.addresses = []
            } catch (error) {
                this.error = error.message || '获取地址失败'
                throw error
            } finally {
                this.isLoading = false
            }
        },

        validateAddress(address) {
            if (!address.name || !address.phone || !address.province ||
                !address.city || !address.district || !address.detail) {
                throw new Error('请填写完整的地址信息')
            }

            if (!/^1[3-9]\d{9}$/.test(address.phone)) {
                throw new Error('请输入正确的手机号码')
            }

            return true
        },

        saveToLocalStorage() {
            localStorage.setItem('user_addresses', JSON.stringify(this.addresses))
        },

        async addAddress(addressData) {
            try {
                this.validateAddress(addressData)

                const newAddress = {
                    ...addressData,
                    id: Date.now(), // 使用时间戳作为ID更可靠
                    isDefault: this.addresses.length === 0 // 如果是第一个地址，设为默认
                }

                this.addresses.push(newAddress)
                this.saveToLocalStorage()

                return newAddress
            } catch (error) {
                this.error = error.message
                throw error
            }
        },

        async updateAddress(updatedAddress) {
            try {
                this.validateAddress(updatedAddress)

                const index = this.addresses.findIndex(a => a.id === updatedAddress.id)
                if (index === -1) {
                    throw new Error('地址不存在')
                }

                this.addresses[index] = updatedAddress
                this.saveToLocalStorage()

                return updatedAddress
            } catch (error) {
                this.error = error.message
                throw error
            }
        },

        async deleteAddress(id) {
            try {
                const index = this.addresses.findIndex(a => a.id === id)
                if (index === -1) {
                    throw new Error('地址不存在')
                }

                const wasDefault = this.addresses[index].isDefault
                this.addresses = this.addresses.filter(a => a.id !== id)

                // 如果删除的是默认地址且还有地址，设置第一个为默认
                if (wasDefault && this.addresses.length > 0) {
                    this.addresses[0].isDefault = true
                }

                this.saveToLocalStorage()
            } catch (error) {
                this.error = error.message
                throw error
            }
        },

        async setDefaultAddress(id) {
            try {
                const index = this.addresses.findIndex(a => a.id === id)
                if (index === -1) {
                    throw new Error('地址不存在')
                }

                this.addresses.forEach(a => {
                    a.isDefault = a.id === id
                })

                this.saveToLocalStorage()
            } catch (error) {
                this.error = error.message
                throw error
            }
        }
    },
    getters: {
        defaultAddress: (state) => state.addresses.find(a => a.isDefault) || null,
        hasAddresses: (state) => state.addresses.length > 0
    }
})
